2166. Anagrams

 

The word is an anagram of another word, if it can be obtained by rearrangement of its letters.

 

Input. Two words are given in different lines. The words consist of lowercase letters and digits. The lengths of each word is no more than 100.

 

Output. Print “YES” if the words are anagrams of each other and “NO” otherwise.

 

Sample input

Sampe output

sharm

marsh

YES

 

 

SOLUTION

sort

 

Algorithm analysis

Sort the letters in each word in lexicographic order. If the obtained words are the same, then they consist of the same letters and thus are anagrams.

 

Algorithm realization

Declare the strings s and q.

 

string s, q;

 

Read the input strings.

 

cin >> s;

cin >> q;

 

Sort the letters in each string.

 

sort(s.begin(),s.end());

sort(q.begin(),q.end());

 

Compare the obtained strings and print the answer.

 

if (s == q) puts("YES"); else puts("NO");

 

Algorithm realizationchar arrays

 

#include <cstdio>

#include <cstring>

#include <algorithm>

using namespace std;

 

char s[100], q[100];

 

int main(void)

{

  gets(s); sort(s,s+strlen(s));

  gets(q); sort(q,q+strlen(q));

  if (strcmp(s,q) == 0) puts("YES"); else puts("NO");

  return 0;

}

 

Algorithm realization – swap sort

 

#include <stdio.h>

#include <string.h>

#define MAX 256

 

char s[MAX], q[MAX];

int slen, qlen;

 

void sort(char *m, int len)

{

  int i, j;

  char temp;

  for(i = 0; i < len; i++)

  for(j = i + 1; j < len; j++)

    if (m[i] > m[j])

    {

      temp = m[i];

      m[i] = m[j];

      m[j] = temp;

    }

}

 

int main(void)

{

  gets(s); slen = strlen(s);

  gets(q); qlen = strlen(q);

 

  sort(s,slen);

  sort(q,qlen);

 

  if (!strcmp(s,q))

    printf("YES\n");

  else

    printf("NO\n");

  return 0;

}

 

Java realization

 

import java.util.*;

 

public class Main

{

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    char[] s = con.nextLine().toCharArray();

    char[] q = con.nextLine().toCharArray();

 

    Arrays.sort(s);

    Arrays.sort(q);

 

    if (Arrays.equals(s, q))

      System.out.println("YES");

    else

      System.out.println("NO");

   

   con.close();   

  }

}

 

Python realization

 

l1 = list(input())

l2 = list(input())

l1.sort()

l2.sort()

if l1 == l2:

  print('YES')

else:

  print('NO')